<template>
  <!-- 特征管理 -->
  <basic-container>
    <avue-crud :defaults.sync="defaults" :option="option" :table-loading="loading" :data="data" :page.sync="page"
      :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate"
      @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">
      <!-- <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">添加
        </el-button>
      </template> -->
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/system/characteristicManage";
import { mapGetters } from "vuex";
import website from "@/config/website";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      defaults: {},
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 5,
        border: true,
        index: true,
        viewBtn: true,
        addBtn: true,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "特征名称",
            prop: "characteristicName",
            search: true,
            rules: [{
              required: true,
              message: "请输入特征名称",
              trigger: "blur"
            }]
          },
          {
            label: "特征类型",
            prop: "characteristicCode",
            type: "select",
            search: true,
            dicUrl: '/api/blade-platform/characteristic/characteristicAbbreviationList',
            rules: [{
              required: true,
              message: "请选择特征类型",
              trigger: "change"
            }]
          },
          // {
          //   label: '水印头像',
          //   prop: 'imgUrl3',
          //   hide: true,
          //   type: 'upload',
          //   // addDisplay: false,
          //   // editDisplay: false,
          //   // viewDisplay: false,

          //   listType: 'picture-img',
          //   accept: 'image/png, image/jpeg',
          //   limit: 2,
          //   fileSize: 10000,
          //   span: 24,
          //   propsHttp: {
          //     res: 'data'
          //   },
          //   tip: '只能上传jpg/png用户头像，且不超过10M',
          //   action: 'https://api.avuejs.com/imgupload'
          // },

          {
            label: "算法类型",
            prop: "characteristicDataType",
            type: "select",
            span: 12,
            dicUrl: '/api/blade-platform/characteristic/dataType',
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }]

          },
          {
            label: '特征描述',
            prop: 'characteristicDescribe',
            // type: 'textarea',
            minRows: 2,
            maxRows: 5,
            hide: true,
            // span: 24
          },
          {
            label: '布尔值',
            prop: 'boolKey',
            // alone: true,
            display: false,
            viewDisplay: false,
            hide: true,
            type: 'url',
            limit: 2,
            value: []
          },
          {
            // label: '单个超链接框',
            prop: 'boolValue',
            // alone: true,
            display: false,
            hide: true,
            type: 'url',
            limit: 2,
            viewDisplay: false,
            value: []
          },
          {
            label: '枚举项',
            prop: 'enumKey',
            type: 'url',
            // alone: true,
            display: false,
            hide: true,
            viewDisplay: false,
            value: []
          },
          {
            // label: '单个超链接框',
            prop: 'enumValue',
            display: false,
            hide: true,
            viewDisplay: false,
            // alone: true,
            type: 'url',
            value: []
          },
          {
            label: '新增时间',
            prop: 'createTime',
            type: 'datetime',
            addDisplay: false,
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            rules: [
              {
                required: true,
                message: '请选择',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否只读',
            prop: 'isReadOnly',
            type: 'radio',
            hide: true,
            span: 24,
            dicData: [{
              label: '是',
              value: true
            }, {
              label: '否',
              value: false
            }],

          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.post_add, false),
        // viewBtn: this.vaildData(this.permission.post_view, false),
        // delBtn: this.vaildData(this.permission.post_delete, false),
        // editBtn: this.vaildData(this.permission.post_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {
    'form.characteristicDataType': {
      handler(val) {
        if (val == 'STRING' || val == 'BOOLEAN') {
          this.defaults.boolKey.display = true
          this.defaults.boolValue.display = true
          this.defaults.enumKey.display = false
          this.defaults.enumValue.display = false
        } else if (val == 'ENUMERATE') {
          this.defaults.boolKey.display = false
          this.defaults.boolValue.display = false
          this.defaults.enumKey.display = true
          this.defaults.enumValue.display = true
        } else {
          this.defaults.boolKey.display = false
          this.defaults.boolValue.display = false
          this.defaults.enumKey.display = false
          this.defaults.enumValue.display = false
        }
      },
      immediate: true
    }
  },
  methods: {
    handleAdd(row) {
      // const statusNew = statusList.find((x) => {
      //   if (x.value == row.offLineStatus) {
      //     return true
      //   }
      // })

      this.$router.push({
        path: '/characteristicManageDetail',
        // query: {
        //   equipmentId: row.equipmentId,
        //   productId: row.productId,
        //   offLineStatus: statusNew.label,
        //   insertTime: row.insertTime,
        // },
      })
    },
    rowSave(row, done, loading) {
      console.log('特征管理添加', JSON.stringify(row))
      const { characteristicName, characteristicCode, characteristicDataType, characteristicDescribe, isReadOnly, boolKey, boolValue, enumKey, enumValue } = row
      const list = []
      if (characteristicDataType == ('STRING' || 'BOOLEAN')) {
        boolKey.forEach((element, index) => {
          list.push({
            characteristicKey: element,
            characteristicPictureUrl: '',
            characteristicValue: boolValue[index]
          })
        });
      } else if (characteristicDataType == 'ENUMERATE') {
        enumKey.forEach((element, index) => {
          list.push({
            characteristicKey: element,
            characteristicPictureUrl: '',
            characteristicValue: enumValue[index]
          })
        });
      } else if (characteristicDataType == 'PICTURE') {
        list.push({
          characteristicKey: '',
          characteristicPictureUrl: '',
          characteristicValue: ''
        })
      }
      const item = {
        characteristicName,
        characteristicCode,
        // className
        characteristicDataType,
        characteristicDescribe,
        isReadOnly,
        list
      }
      console.log('特征管理添加-处理数据', JSON.stringify(item))
      add(item).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      console.log('特征管理添加', JSON.stringify(row))
      const { id, characteristicName, characteristicCode, characteristicDataType, characteristicDescribe, isReadOnly, boolKey, boolValue, enumKey, enumValue } = row
      const list = []
      if (characteristicDataType == ('STRING' || 'BOOLEAN')) {
        boolKey.forEach((element, index) => {
          list.push({
            characteristicKey: element,
            characteristicPictureUrl: '',
            characteristicValue: boolValue[index]
          })
        });
      } else if (characteristicDataType == 'ENUMERATE') {
        enumKey.forEach((element, index) => {
          list.push({
            characteristicKey: element,
            characteristicPictureUrl: '',
            characteristicValue: enumValue[index]
          })
        });
      } else if (characteristicDataType == 'PICTURE') {
        list.push({
          characteristicKey: '',
          characteristicPictureUrl: '',
          characteristicValue: ''
        })
      }
      const item = {
        id,
        characteristicName,
        characteristicCode,
        // className
        characteristicDataType,
        characteristicDescribe,
        isReadOnly,
        list
      }
      console.log('特征管理编辑-处理数据', JSON.stringify(item))
      update(item).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          const data = res.data.data
          const list = data.characteristicDataTableVOS
          list.forEach((element) => {
            if (data.characteristicDataType == ('STRING' || 'BOOLEAN')) {
              this.form.boolKey.push(element.characteristicKey)
              this.form.boolValue.push(element.characteristicValue)
            } else if (data.characteristicDataType == 'ENUMERATE') {
              this.form.enumKey.push(element.characteristicKey)
              this.form.enumValue.push(element.characteristicValue)
            } else if (data.characteristicDataType == 'PICTURE') {
              // this.form.enumKey.push(element.characteristicKey)
              // this.form.enumValue.push(element.characteristicValue)
              // list.push({
              //   characteristicKey: '',
              //   characteristicPictureUrl: '',
              //   characteristicValue: ''
              // })
            }

          });


          // this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
